from fastapi import APIRouter, Depends
from datetime import timedelta
from ..models.models import LoginRequest
from ..utils.auth import authenticate_user, create_access_token, get_current_user
from ..utils.response import APIResponse
from ..config import settings

router = APIRouter(prefix="/auth", tags=["authentication"])

@router.post("/login")
async def login(login_data: LoginRequest):
    """用户登录"""
    try:
        user = authenticate_user(login_data.user_id, login_data.password, login_data.role)
        if not user:
            return APIResponse.error("用户名或密码错误", 401)
        
        # 创建访问令牌数据
        access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_access_token(
            data={"sub": user["id"], "name": user["name"], "role": user["role"]}, 
            expires_delta=access_token_expires
        )
        
        return APIResponse.success({
            "access_token": access_token,
            "token_type": "bearer",
            "user_info": user
        }, "登录成功")
    
    except Exception as e:
        return APIResponse.error(f"登录失败: {str(e)}", 500)

@router.get("/me")
async def get_current_user_info(current_user: dict = Depends(get_current_user)):
    """获取当前用户信息"""
    try:
        return APIResponse.success({
            "id": current_user["id"],
            "name": current_user["name"],
            "role": current_user["role"],
            "major": current_user.get("major"),
            "title": current_user.get("title")
        }, "获取用户信息成功")
    
    except Exception as e:
        return APIResponse.error(f"获取用户信息失败: {str(e)}", 500) 